//
//  MBDIntegrationDetailViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/5/14.
//

import Foundation
import UIKit
import YYText
import SnapKit
import MJRefresh
import Toast_Swift

class MBDIntegrationDetailViewController : MBDBaseViewController {
    
    var tableView : UITableView!
    var pageIndex : Int!

    var viewModel : MBDIntegrationDetailViewModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.pageIndex = 1

        self.title = "积分明细"
        self.viewModel = MBDIntegrationDetailViewModel()

        tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.allowsMultipleSelection = false
        tableView.allowsSelectionDuringEditing = false
        tableView.allowsMultipleSelectionDuringEditing = false
        self.view.addSubview(tableView)
        
        NSLayoutConstraint.activate([
        self.view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: tableView.topAnchor),
                    self.view.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
                    self.view.leadingAnchor.constraint(equalTo: tableView.leadingAnchor),
                    self.view.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
                ])
        tableView.setDynamicBackgroundColor()
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.rowHeight = 100
        
        tableView.register(MBDIntegrationDetailCell.self, forCellReuseIdentifier: "MBDIntegrationDetailCell")
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            [unowned self] in
            self.pageIndex = 1
            self.tableView.mj_footer?.resetNoMoreData()
            
            self.viewModel.doRequest { error,result, totalPage,integrateTotal in
                if nil != error {
                    self.view.makeToast(error?.localizedDescription,position: .center)
                } else {
                    self.viewModel.cellModels = result
                    self.tableView.reloadData()
                                    
                    self.tableView.mj_header?.endRefreshing()
                    if self.pageIndex >= totalPage {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.resetNoMoreData()
                    }
                }
                
            }
        })
        
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            [unowned self] in
            
            self.pageIndex += 1
            self.viewModel.doRequest(pageNum: self.pageIndex, completion: { error,result, totalPage,integrateTotal in
                
                if nil != error {
                    self.view.makeToast(error?.localizedDescription,position: .center)
                } else {
                    var integrates = Array<Any>()
                    integrates.append(contentsOf: self.viewModel.cellModels ?? Array<Any>())
                    
                    if result?.count ?? 0 > 0 {
                        integrates.append(contentsOf: result!)
                    }
                    
                    self.viewModel.cellModels = integrates
                    self.tableView.reloadData()
                    
                    self.tableView.mj_footer?.endRefreshing()
                    
                    if self.pageIndex >= totalPage {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                }
                
            })
        })
        
        self.view.setDynamicBackgroundColor()
        tableView.setDynamicBackgroundColor()
    }
    
    func refreshUI(){
        self.pageIndex = 1
        self.viewModel.doRequest { error,result, totalPage,integrateTotal in
            
            if nil != error {
                self.view.makeToast(error?.localizedDescription,position: .center)
            } else {
                
                if result?.count ?? 0 > 0 {
                    self.viewModel.cellModels = result
                    self.tableView.reloadData()
                } else {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    
                    self.tableView.setEmptyView(title: "数据为空，可能出了点问题",
                                                       message: "")
                }
                
                if totalPage == 1 {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self.tableView.mj_footer?.resetNoMoreData()
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshUI()
    }
    
    override func updateColors() {
        view.setDynamicBackgroundColor()
        tableView.setDynamicBackgroundColor()

        // 遍历并更新 cellModels
        var result = Array<Any>()
        if let cellModels = self.viewModel.cellModels {
            for i in 0..<cellModels.count {
                let cellModel = cellModels[i]
                if (cellModel as AnyObject).isKind(of: MBDIntegrationDetailCellModel.self) {
                    let realCellModel = cellModel as! MBDIntegrationDetailCellModel
                    let intergral = realCellModel.integrationDetail
                    realCellModel.integrationDetail = intergral
                }
                result.append(cellModel)
            }
        }
        self.viewModel.cellModels = result
        self.tableView.reloadData()
    }
}

extension MBDIntegrationDetailViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.cellModels?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        if cellModel is MBDIntegrationDetailCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDIntegrationDetailCell", for: indexPath)
            let realCell = cell as! MBDIntegrationDetailCell
            realCell.cellModel = cellModel
            return cell

        } else {
            return UITableViewCell()
        }

    }
}


extension MBDIntegrationDetailViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let vc = MBDGroupModifyViewController()
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let realCellModel = cellModel as! MBDCommonCellModel
        return realCellModel.cellHeight()
    }
}


class MBDIntegrationDetailCell: MBDCommonCell {

    var consumptionLabel : YYLabel!
    var timeLabel : YYLabel!
    var priceDetailLabel : YYLabel!

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.initialize()
    }
    
    override var cellModel: Any! {
        didSet {
            let cellModel = self.cellModel as! MBDIntegrationDetailCellModel
            
            self.integrateDetail = cellModel.integrationDetail
            self.location = cellModel.location
        }
    }

    func initialize() {
        self.contentView.setDynamicForgroundColor()
        self.commonBackgroundView.setDynamicForgroundColor()

        consumptionLabel = YYLabel()
        self.contentView.addSubview(consumptionLabel)
        
        timeLabel = YYLabel()
        self.contentView.addSubview(timeLabel)
        
        priceDetailLabel = YYLabel()
        priceDetailLabel.textColor = .red
        priceDetailLabel.textAlignment = .right
        priceDetailLabel.font = UIFont.systemFont(ofSize: 28)
        self.commonBackgroundView.addSubview(priceDetailLabel)
        
        consumptionLabel.snp.makeConstraints { make in
            make.left.equalTo(MBDIntegrationDetailCellModel.consumptionLeftMargin)
            make.top.equalTo(MBDIntegrationDetailCellModel.topMargin)
            make.right.lessThanOrEqualTo(self.priceDetailLabel.snp.left).offset(-MBDIntegrationDetailCellModel.priceDetailLabelLeftMargin)
            make.height.equalTo(0)
        }
        
        timeLabel.snp.makeConstraints { make in
            make.left.equalTo(consumptionLabel)
            make.top.equalTo(consumptionLabel.snp.bottom).offset(MBDIntegrationDetailCellModel.marginBetweenConsumptionAndTime)
            make.right.lessThanOrEqualTo(self.priceDetailLabel.snp.left).offset(-MBDIntegrationDetailCellModel.priceDetailLabelLeftMargin)
            make.height.equalTo(16)
        }
        
        priceDetailLabel.snp.makeConstraints { make in
            make.right.equalTo(self.contentView).offset(-MBDIntegrationDetailCellModel.priceDetailLabelRightMargin)
            make.width.equalTo(MBDIntegrationDetailCellModel.priceDetailLabelWidth)
            make.centerY.equalTo(self.contentView)
        }
    }
    
    var integrateDetail : MBDIntegrateExpDetailModel? {
        didSet {
            let cellModel = self.cellModel as! MBDIntegrationDetailCellModel
            
            consumptionLabel.textLayout = cellModel.consumptionLayout
            consumptionLabel.snp.updateConstraints { make in
                let height = cellModel.consumptionLayout!.textBoundingRect.height
                make.height.equalTo(height)
            }
            
            timeLabel.textLayout = cellModel.timeLayout

            timeLabel.snp.updateConstraints { make in
                let height = cellModel.timeLayout!.textBoundingSize.height
                make.height.equalTo(height)
            }
            
            priceDetailLabel.text = integrateDetail?.integralNumber
        }
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
    }

}
